﻿@{
    ViewData["Title"] = "BOMShow";
}

<!-- Basic Information Section -->
<div class="container mt-4">
    <h2 class="mb-4">基础信息</h2>
    <div class="row">
        <!-- Left Column -->
        <div class="col-md-6">
            <div class="mb-3">
                <label class="form-label">* BOM编号</label>
                <div class="input-group">
                    <input type="text" class="form-control" id="bomNumber" value="BOM0000516258" />
                    <div class="input-group-text">
                        <input type="checkbox" id="systemNumber" checked />
                        <label class="ms-2 mb-0" for="systemNumber">系统编号</label>
                    </div>
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label">* 默认BOM</label>
                <div>
                    <input type="checkbox" id="defaultBOM" />
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label">* 成品类型</label>
                <select class="form-select" id="productType">
                    <option value="">请选择成品类型</option>
                    <option value="类型一">类型一</option>
                    <option value="类型二">类型二</option>
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label">日产量</label>
                <input type="text" class="form-control" id="dailyOutput" placeholder="请输入日产量" />
            </div>

            <div class="mb-3">
                <label class="form-label">备注</label>
                <textarea class="form-control" id="remarks" rows="3" placeholder="请输入备注"></textarea>
            </div>
        </div>

        <!-- Right Column -->
        <div class="col-md-6">
            <div class="mb-3">
                <label class="form-label">* BOM主题</label>
                <input type="text" class="form-control" id="bomSubject" placeholder="请输入BOM主题" />
            </div>

            <div class="mb-3">
                <label class="form-label">* 版本</label>
                <input type="text" class="form-control" id="version" placeholder="请输入版本" />
            </div>

            <div class="mb-3">
                <label class="form-label">* 成品名称</label>
               @*  <div class="input-group">
                    <input type="text" class="form-control" id="productName" placeholder="请选择物品" />
                    <button class="btn btn-outline-secondary" type="button" id="selectProductBtn">
                        <i class="bi bi-box"></i>
                    </button>
                </div> *@
                <select class="form-select" id="productName">
                   
                </select>
            </div>
        </div>
    </div>
</div>
<h1 class="mt-4">BOM配件管理</h1>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#itemModal">
                新增
            </button>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-12">
            <table class="table table-bordered" id="bomTable">
                <thead>
                    <tr>
                        <th>物品编号</th>
                        <th>物品名称</th>
                        <th>规格型号</th>
                        <th>单位</th>
                        <th>品牌</th>
                        <th>配件数量</th>
                        <th>损耗率</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Rows will be added dynamically -->
                </tbody>
            </table>
        </div>
    </div>


</div>

<!-- 工艺流程 Section -->
<div class="container mt-5">
    <h1 class="mt-4">工艺流程</h1>
    <div class="row">
        <div class="col-md-12">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#processModal" id="openProcessModal">
                新增
            </button>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-12">
            <table class="table table-bordered" id="processTable">
                <thead>
                    <tr>
                        <th>工序编码</th>
                        <th>工序名称</th>
                        <th>加工顺序</th>
                        <th>工艺流程</th>
                        <th>负责人</th>
                        <th>部门</th>
                        <th>单位工作量</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12 text-center">
            <button type="button" class="btn btn-success" id="confirmBtn" onclick="createBom()">确定</button>
        </div>
    </div>
</div>

<!-- Modal for selecting items -->
<div class="modal fade" id="itemModal" tabindex="-1" aria-labelledby="itemModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="itemModalLabel">选择物品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <table class="table table-bordered" >
                    <thead>
                        <tr>
                            <th style="width:60px;"><input type="checkbox" id="checkAll" /></th>
                            <th>物品编号</th>
                            <th>物品名称</th>
                            <th>规格型号</th>
                            <th>单位</th>
                            <th>品牌</th>
                        </tr>
                    </thead>
                    <tbody id ="itemTable">
                        <!-- Items will be loaded via AJAX -->
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="addSelectedItems()">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- Process select modal -->
<div class="modal fade" id="processModal" tabindex="-1" aria-labelledby="processModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="processModalLabel">选择工艺</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th style="width:60px;"><input type="checkbox" id="checkAllProcess" /></th>
                            <th>工序编码</th>
                            <th>工序名称</th>
                        </tr>
                    </thead>
                    <tbody id="processModalTable">
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="addSelectedProcesses()">确定</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>

    $(function () {
        GetBOM_Accessories();
        GetBOM_Process();
        GetProduct();
        // 全选/反选
        $(document).on('change', '#checkAll', function(){
            $('#itemTable').find('input.item-check').prop('checked', $(this).prop('checked'));
        });

        // 若子项改变，更新全选框状态
        $(document).on('change', 'input.item-check', function(){
            var all = $('input.item-check').length;
            var checked = $('input.item-check:checked').length;
            $('#checkAll').prop('checked', all > 0 && all === checked);
        });

        // 系统编号自动生成
        $('#systemNumber').on('change', function(){
            if (this.checked) {
                $('#bomNumber').val(generateBomNumber());
            }
        });

        // 打开工艺弹窗时加载列表
        $('#openProcessModal').on('click', function(){
            loadProcessList();
        });

        // 工艺弹窗全选
        $(document).on('change', '#checkAllProcess', function(){
            $('#processModalTable').find('input.proc-check').prop('checked', $(this).prop('checked'));
        });
    })

    function pad2(n){return n<10 ? '0'+n : ''+n}
    function generateBomNumber(){
        var d = new Date();
        var y = d.getFullYear();
        var m = pad2(d.getMonth()+1);
        var day = pad2(d.getDate());
        // 4位随机数，避免重复
        var rand = Math.floor(1000 + Math.random()*9000);
        return 'BOM' + y + m + day + rand;
    }



    function GetProduct() {
        $.ajax({
            url: 'http://localhost:5280/api/WookOrder/GetprocuctHandle',
            type: 'get',
            data: {},
            async: false,
            success: function (res) {
                console.log('产品列表响应:', res);
                var list = [];
                if (res && Array.isArray(res)) {
                    list = res;
                } else if (res && Array.isArray(res.pageData)) {
                    list = res.pageData;
                } else if (res && res.data && Array.isArray(res.data)) {
                    list = res.data;
                }

                var html = '<option value="">请选择成品名称</option>';
                if (list.length > 0) {
                    $(list).each(function () {
                        var id = this.id || this.Id || this.ID || '';
                        var name = this.product_Name || this.productName || this.name || '';
                        if (id !== '' && name !== '') {
                            html += `<option value="${name}">${name}</option>`;
                        }
                    });
                } else {
                    console.warn('产品列表为空，无法渲染下拉框');
                }
                $('#productName').html(html);
            },
            error: function (xhr) {
                console.error('加载产品列表失败:', xhr.status, xhr.responseText);
                $('#productName').html('<option value="">加载失败</option>');
            }
        });
    }
    function GetBOM_Accessories() {
        $.ajax({
            url: "http://localhost:5280/api/WookOrder/GetBOM_AccessoriesHandle",
            type: "get",
            data: {},
            async: false,
            success: function (res) {
                var str = ``;
                $(res.pageData).each(function () {
                    var itemId = this.id || this.Id || this.ID; // 兼容不同大小写
                    var serial = this.serial_Number || this.serialNumber || this.Serial_Number || '';
                    var name = this.item_Name || this.itemName || this.Item_Name || '';
                    var spec = this.specification_Model || this.spec || this.Specification_Model || '';
                    var unit = this.unit || this.Unit || '';
                    var brand = this.brand || this.Brand || '';
                    str += `<tr>
                                <td><input type="checkbox" class="item-check" data-id="${itemId}" data-code="${serial}" data-name="${name}" data-spec="${spec}" data-unit="${unit}" data-brand="${brand}"></td>
                                <td>${serial}</td>
                                <td>${name}</td>
                                <td>${spec}</td>
                                <td>${unit}</td>
                                <td>${brand}</td>
                            </tr>`;
                });
                $("#itemTable").html(str);
                $('#checkAll').prop('checked', false);
            }
        });

    }
        function GetBOM_Process() {
            $.ajax({
                url: "http://localhost:5280/api/WookOrder/Process_FlowHandle",
                type: "get",
                data: {},
                async: false,
                success: function (res) {
                    var str = '';
                    var list = (res && res.pageData) ? res.pageData : [];
                    $(list).each(function () {
                        var itemId = this.id || this.Id || this.ID; // 兼容不同大小写
                        var code = this.process_Code || this.Process_Code || this.processCode || this.code || '';
                        var name = this.process_Name || this.Process_Name || this.processName || this.name || '';
                        str += `<tr>
                                    <td><input type="checkbox" class="proc-check" data-id="${itemId}" data-code="${code}" data-name="${name}"></td>
                                    <td>${code}</td>
                                    <td>${name}</td>
                                </tr>`;
                    });
                    $("#processModalTable").html(str);
                    $('#checkAllProcess').prop('checked', false);
                },
                error: function(xhr){
                    console.error('加载工艺列表失败:', xhr.status, xhr.responseText);
                    $("#processModalTable").html('<tr><td colspan="3" class="text-center">加载失败</td></tr>');
                }
            });
        }




    // 将选中项添加到下方BOM表格
    function addSelectedItems(){
        var selected = $('input.item-check:checked');
        if(selected.length === 0){
            alert('请选择至少一条数据');
            return;
        }
        selected.each(function(){
            var id = $(this).data('id');
            // 防重复：如果已存在同id的行则跳过
            if($('#bomTable tbody tr[data-id="'+id+'"]').length > 0){
                return;
            }
            var code = $(this).data('code');
            var name = $(this).data('name');
            var spec = $(this).data('spec');
            var unit = $(this).data('unit');
            var brand = $(this).data('brand');
            var row = `<tr data-id="${id}">
                            <td>${code}</td>
                            <td>${name}</td>
                            <td>${spec}</td>
                            <td>${unit}</td>
                            <td>${brand}</td>
                            <td><input type="number" class="form-control qty-input" value="1" min="1" step="1"></td>
                            <td><input type="number" class="form-control loss-input" value="0" min="0" step="0.01"></td>
                            <td><button class="btn btn-danger btn-sm" onclick="$(this).closest('tr').remove()">移除</button></td>
                        </tr>`;
            $('#bomTable tbody').append(row);
        });
        // 关闭弹窗（强制清理遮罩）
        var modalEl = document.getElementById('itemModal');
        var modal = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
        modal.hide();
        setTimeout(function(){
            $('.modal-backdrop').remove();
            $('body').removeClass('modal-open').css('padding-right','');
        }, 150);
    }

    // 加载工艺列表（弹窗）
    function loadProcessList(){
        $.ajax({
            url: "http://localhost:5280/api/WookOrder/Process_FlowHandle",
            type: "get",
            data: {},
            async: false,
            success: function(res){
                var html = '';
                var list = res.pageData || [];
                $(list).each(function(){
                    var pid = this.id || this.Id || this.ID;
                    var code = this.process_Code || this.Process_Code || this.processCode || this.code || '';
                    var name = this.process_Name || this.Process_Name || this.processName || this.name || '';
                    html += `<tr>
                                <td><input type="checkbox" class="proc-check" data-id="${pid}" data-code="${code}" data-name="${name}"></td>
                                <td>${code}</td>
                                <td>${name}</td>
                            </tr>`;
                });
                $('#processModalTable').html(html);
                $('#checkAllProcess').prop('checked', false);
            },
            error: function(xhr){
                console.error('加载工艺列表失败:', xhr.status, xhr.responseText);
                $('#processModalTable').html('<tr><td colspan="3" class="text-center">加载失败</td></tr>');
            }
        });
    }

    // 将选中的工艺添加到工艺表格
    function addSelectedProcesses(){
        var selected = $('input.proc-check:checked');
        if(selected.length === 0){
            alert('请选择至少一条工艺');
            return;
        }
        selected.each(function(){
            var id = $(this).data('id');
            if($('#processTable tbody tr[data-id="'+id+'"]').length > 0){
                return;
            }
            var code = $(this).data('code');
            var name = $(this).data('name');
            var row = `<tr data-id="${id}">
                        <td>${code}</td>
                        <td>${name}</td>
                        <td style="width:110px"><input type="number" class="form-control seq-input" value="1" min="1" step="1"></td>
                        <td><input type="text" class="form-control flow-input" placeholder="请输入工艺流程"></td>
                        <td><input type="text" class="form-control resp-input" placeholder="负责人"></td>
                        <td><input type="text" class="form-control dept-input" placeholder="部门"></td>
                        <td style="width:130px"><input type="number" class="form-control work-input" value="0" min="0" step="1"></td>
                        <td><input type="text" class="form-control remark-input" placeholder="备注"></td>
                        <td><button class="btn btn-danger btn-sm" onclick="$(this).closest('tr').remove()">移除</button></td>
                    </tr>`;
            $('#processTable tbody').append(row);
        });

        var modalEl = document.getElementById('processModal');
        var modal = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
        modal.hide();
        setTimeout(function(){
            $('.modal-backdrop').remove();
            $('body').removeClass('modal-open').css('padding-right','');
        }, 150);
    }

    function createBom() { 
        // 从下方BOM表格收集配件数据
        var accessoriesArr = [];
        $('#bomTable tbody tr').each(function(){
            var idRaw = $(this).data('id') || $(this).attr('data-id');
            var id = parseInt(idRaw, 10);
            if (isNaN(id)) {
                // 如果id无法解析为数字则跳过此行
                return true; // continue
            }
            var qty = parseFloat($(this).find('.qty-input').val());
            var loss = parseFloat($(this).find('.loss-input').val());
            if (isNaN(qty)) qty = 0;
            if (isNaN(loss)) loss = 0;
            accessoriesArr.push({
                "createUserId": 0,
                "upDataUserId": 0,
                "createTime": new Date().toISOString(),
                "upDataTime": new Date().toISOString(),
                "isDel": false,
                "accessories_ID": id,
                "accessories_Number": qty,
                "attrition_Rate": loss
            });
        });

        // 收集工艺流程数据
        var processArr = [];
        $('#processTable tbody tr').each(function(){
            var pidRaw = $(this).data('id') || $(this).attr('data-id');
            var pid = parseInt(pidRaw, 10);
            if (isNaN(pid)) return true;
            var seq = $(this).find('.seq-input').val();
            var flows = $(this).find('.flow-input').val();
            var person = $(this).find('.resp-input').val();
            var dept = $(this).find('.dept-input').val();
            var unitWork = parseFloat($(this).find('.work-input').val());
            if (isNaN(unitWork)) unitWork = 0;
            var note = $(this).find('.remark-input').val();
            processArr.push({
                "createUserId": 0,
                "upDataUserId": 0,
                "createTime": new Date().toISOString(),
                "upDataTime": new Date().toISOString(),
                "isDel": false,
                "basic_ID": 0,
                "process_ID": pid,
                "processing_Sequence": String(seq || ''),
                "process_Flows": String(flows || ''),
                "person_Charge": String(person || ''),
                "department": String(dept || ''),
                "unit_Workload": unitWork,
                "notes": String(note || '')
            });
        });

        if (accessoriesArr.length === 0) {
            alert('请先在下方表格添加至少一个配件');
            return;
        }

        var obj = {
            "boM_Number": $("#bomNumber").val(),
            "boM_Theme": $("#bomSubject").val(),
            "default_BOM": $("#defaultBOM").is(':checked'),
            "version": $("#version").val(),
            "product_Type": $("#productType").val(),
            "product_Name": $("#productName").val(),
            "daily_Output": String($("#dailyOutput").val() || ''),
            "notes": $("#remarks").val(),
            "accessories": accessoriesArr.map(function(a){
                return Object.assign({}, a, { basic_ID: 0 });
            }),
            "process": processArr
        }

        // 调试：打印最终请求体
        console.log('Create BOM payload =>', obj);

        $.ajax({
            url: "http://localhost:5280/api/WookOrder/CreateBasic_InformationHandle",
            type: "post",
            data: JSON.stringify(obj),
            dataType: "json",
            contentType: "application/json",
            success: function (res, status, xhr) {
                console.log('Create BOM response =>', res, 'status:', status, 'http:', xhr.status);
                if ((typeof res === 'number' && res > 0) || (res && res.code === 200)) {
                    alert("添加成功");
                    location.href = '/home/GetBom';
                }
                else {
                    alert("添加失败: " + JSON.stringify(res));
                }
            },
            error: function (xhr) {
                console.error('Create BOM error =>', xhr.status, xhr.responseText);
                alert('添加失败: HTTP ' + xhr.status + ' ' + (xhr.responseText || '')); 
            }
        })

    }

</script>